﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;

namespace HospitalSystem.Admin
{
    public partial class AdminManagement : System.Web.UI.Page
    {
        DataTable dt = new DataTable();
        DataTable dx = new DataTable();
        string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;
        public static string key = "MDCODE";
        string PasswordChangeSQL = WebConfigurationManager.AppSettings["PasswordChangeSQL"];
        string AdminEmail = WebConfigurationManager.AppSettings["AdminEmail"];
        string AdminPassword = WebConfigurationManager.AppSettings["AdminPassword"];
        string ActivatedStatusTrueSQL = WebConfigurationManager.AppSettings["ActivatedStatusTrueSQL"];
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
            
        }
        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }
        protected void BindData()
        {
            SqlConnection scon = new SqlConnection(constr);
            if (dt.Columns.Count <= 0)
            {
                dt.Columns.Add("Staff_id");
                dt.Columns.Add("Firstname");
                dt.Columns.Add("Lastname");
                dt.Columns.Add("Username");
                dt.Columns.Add("Email");
                dt.Columns.Add("Activated");

                dx.Columns.Add("Staff_id");
                dx.Columns.Add("Firstname");
                dx.Columns.Add("Lastname");
                dx.Columns.Add("Username");
                dx.Columns.Add("Email");
                dx.Columns.Add("Activated");
            }
            SqlCommand cmd = new SqlCommand("SELECT Staff_id,Firstname,Lastname,Username,Email,Activated FROM Employee WHERE Activated = 0", scon);
            SqlCommand cmd2 = new SqlCommand("SELECT Staff_id,Firstname,Lastname,Username,Email,Activated FROM Employee WHERE Activated <> 0", scon);
            scon.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read() != false)
            {
                dt.Rows.Add(reader["Staff_id"].ToString(), reader["Firstname"].ToString(), reader["Lastname"].ToString(), reader["Username"].ToString(), reader["Email"].ToString(), reader["Activated"].ToString());
            }
            reader.Close();
            GridView1.DataSource = dt;
            GridView1.DataBind();
            scon.Close();

            scon.Open();
            SqlDataReader reader2 = cmd2.ExecuteReader();
            while (reader2.Read() != false)
            {
                dx.Rows.Add(reader2["Staff_id"].ToString(), reader2["Firstname"].ToString(), reader2["Lastname"].ToString(), reader2["Username"].ToString(), reader2["Email"].ToString(), reader2["Activated"].ToString());
            }
            reader.Close();
            GridView2.DataSource = dx;
            GridView2.DataBind();
            scon.Close();
        }
        protected void ApproveButton_Click(object sender, EventArgs e)
        {
            
            try
            {
                SqlConnection scon = new SqlConnection(constr);
                foreach (GridViewRow row in GridView1.Rows)
                {
                    RadioButtonList RBLT = (RadioButtonList)row.FindControl("RBL");
                    SqlCommand command = new SqlCommand(PasswordChangeSQL, scon);
                    command.Parameters.AddWithValue("@Activated", RBLT.SelectedValue.ToString());
                    command.Parameters.AddWithValue("@Staff_id", GridView1.Rows[row.RowIndex].Cells[0].Text);
                    scon.Open();
                    command.ExecuteNonQuery();
                    scon.Close();
                }
                dt.Clear();
                dx.Clear();
                BindData();
            }
            catch
            {
                MessageBox("HaHAHAHAHAHAHAHhA!!!!!!!");
            }       
        }

        public string Decrypt(string strEncrypted, string strKey)
        {
            try
            {
                TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
                MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

                byte[] byteHash, byteBuff;
                string strTempKey = strKey;

                byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
                objHashMD5 = null;
                objDESCrypto.Key = byteHash;
                objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

                byteBuff = Convert.FromBase64String(strEncrypted);
                string strDecrypted = ASCIIEncoding.ASCII.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
                objDESCrypto = null;

                return strDecrypted;
            }
            catch (Exception ex)
            {
                return "Wrong Input. " + ex.Message;
            }
        }

        private void SendMail(string MailF)
        {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                MailMessage eMail = new MailMessage();
                eMail.To.Add(MailF);
                eMail.From = new System.Net.Mail.MailAddress("ck_gilgamaze@windowslive.com");
                eMail.Subject = "PasswordRecovery";
                eMail.Body = PasswordRecov(MailF);
                //Smtp hostด้านล่างให้เลือกใส่บริการ Host ที่email admin ใช้ส่ง
                //--------------------------------------------------------------------------------------------------
                //Gmail
                //smtp.gmail.com
                //SSL Port 465
                //StartTLS Port 587

                //--------------------------------------------------------------------------------------------------
                //Outlook
                //smtp.live.com
                //StartTLS Port 587

                //--------------------------------------------------------------------------------------------------
                //Yahoo mail/plus
                //smtp.mail.yahoo.com
                //plus.smtp.mail.yahoo.com
                //SSL Port 465

                //--------------------------------------------------------------------------------------------------
                //Hotmail
                //smtp.live.com
                //StartTLS Port 587
                //--------------------------------------------------------------------------------------------------
                System.Net.NetworkCredential NC = new System.Net.NetworkCredential();
                NC.UserName = "ck_gilgamaze@windowslive.com";
                NC.Password = "0838721407g";
                string temps = NC.UserName.ToString();
                string[] smtptype = temps.Split('@');
                string ptype = mailSMTP(smtptype[1]);
                int pport = mailPort(smtptype[1]);
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(ptype);
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = NC;
                smtp.EnableSsl = true;
                smtp.Port = pport;
                smtp.Send(eMail);
        }

        private string PasswordRecov(string emailX)
        {
            SqlConnection scon = new SqlConnection(constr);
            string cov = "";
            scon.Open();
            SqlCommand cmd = new SqlCommand("SELECT Password FROM Employee WHERE Email = @sj", scon);
            cmd.Parameters.AddWithValue("@sj", emailX);
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read() != false)
            {
                cov = reader["Password"].ToString();
            }
            reader.Close();
            scon.Close();
            return Decrypt(cov, key);

        }

        private int mailPort(string stp)
        {
            if ((stp == "Hotmail.com") || (stp == "hotmail.com") || (stp == "Windowslive.com") || (stp == "windowslive.com"))
            {
                return 587;
            }
            else if ((stp == "Gmail.com") || (stp == "gmail.com"))
            {
                return 465;
            }
            else if ((stp == "Yahoo.com") || (stp == "yahoo.com"))
            {
                return 465;
            }
            else
            {
                return 0;
            }
        }

        private string mailSMTP(string stp)
        {
            if ((stp == "Hotmail.com") || (stp == "hotmail.com") || (stp == "Windowslive.com") || (stp == "windowslive.com"))
            {
                return "smtp.live.com";
            }
            else if ((stp == "Gmail.com") || (stp == "gmail.com"))
            {
                return "smtp.gmail.com";
            }
            else if ((stp == "Yahoo.com") || (stp == "yahoo.com"))
            {
                return "smtp.mail.yahoo.com";
            }
            else
            {
                return "error";
            }
        }
    }
}